﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Android.App;
using UniversalApproach.Expands;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Medicine.Models
{
    public class BAdapter<T> : BaseAdapter<T>
        where T : BaseModel, new()
    {
        protected Activity _context;
        private Expression<Func<T, bool>> _expression;
        protected List<T> _data;

        public override T this[int position]
        {
            get
            {
                return _data[position];
            }
        }

        public override int Count
        {
            get
            {
                return _data.Count;
            }

        }

        public BAdapter()
            : base()
        {

        }

        public BAdapter(Activity context, Expression<Func<T, bool>> expression = null)
            : this()
        {
            this._context = context;
            this._expression = expression;
            SetData();
        }

        /// <summary>
        /// 默认设置数据
        /// </summary>
        public virtual void SetData()
        {
            if (this._expression == null)
                _data = DbContext.DbC.AllDataQuery<T>();
            else
                _data = DbContext.DbC.ListQuery<T>(this._expression);

            if (typeof(T).Name == nameof(Models.Medicine))
            {
                _data = _data.OrderBy(nameof(Models.Medicine.ExpirationDate)).ToList();
            }
        }

        /// <summary>
        /// 更改查询表达式
        /// </summary>
        /// <param name="expression"></param>
        public void SetQueryExpression(Expression<Func<T, bool>> expression)
            => this._expression = expression;

        public void SetData(List<T> data)
            => _data = data;


        public override long GetItemId(int position)
            => position;

        /// <summary>
        /// 通知数据更新
        /// </summary>
        public override void NotifyDataSetChanged()
        {
            SetData();
            base.NotifyDataSetChanged();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="position"></param>
        /// <param name="convertView"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            throw new NotImplementedException();
        }
    }
}